/*cloneable 接口是一个特殊的接口，它是一个标志接口，即什么都没有
 *在需要克隆一个类时，这个类要实现Cloneable，并抛出异常，才能使用clone方法
 */

class Money implements Cloneable{//需要实现
    public double m = 12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {//重写方法
        return super.clone();
    }
}

class Person implements Cloneable{
    public int age;
    public Money money = new Money();//类内部调用一个类

    public void eat() {
        System.out.println("吃！");
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //实现了一个浅拷贝
        Person tmp = (Person)super.clone();
        tmp.money = (Money) this.money.clone();
        return tmp;
        //return super.clone();
    }
}
public class TestDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        Person person2 = (Person)person.clone();
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
        System.out.println("=====================");
        //因为是对象会指向同一个值，所以本来会同时改
        //这里实现了浅拷贝，改变克隆类内的对象的值不会改变原来。
        person2.money.m = 99.99;
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
    }


    public static void main1(String[] args) throws CloneNotSupportedException {
        //深拷贝示例
        Person person = new Person();
        person.age = 99;

        Person person2 = (Person)person.clone();//clone返回的是object对象，需要强转
        System.out.println(person2);

        System.out.println("==================");
        person2.age = 199;
        //改变克隆对象的值不会影响我原来的值
        System.out.println(person);
        System.out.println(person2);

    }
}
